package com.choco.jsondb.utils;

import com.choco.jsondb.Context;

import java.io.*;

public class FileUtil {
    public static boolean write(Context context, Object object){
        boolean success = false;
        java.io.File file = new java.io.File(context.getFile());
        ObjectOutputStream oos = null;

        try {
            oos = new ObjectOutputStream( new FileOutputStream(file));
            oos.writeObject(object);
            success = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                oos.flush();
                oos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return success;
    }

    public static Object read(Context context){
        Object pairs = null;

        java.io.File file = new java.io.File(context.getFile());
        ObjectInputStream ois = null;

        try {
            ois = new ObjectInputStream(new FileInputStream(file));
            pairs = ois.readObject();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }finally{
            try {
                ois.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return pairs;
    }
}
